package com.dongbao.dialog;

import com.alibaba.fastjson.JSON;
import com.dongbao.data.Datacenter;
import com.dongbao.dialog.view.component.MyLanguageTextField;
import com.dongbao.entity.AuditFileInfo;
import com.dongbao.entity.AuditInfo;
import com.dongbao.entity.EditorHighlighterEx;
import com.dongbao.entity.MqMessage;
import com.dongbao.service.MyMqttClient;
import com.intellij.diff.DiffContentFactoryEx;
import com.intellij.diff.DiffDialogHints;
import com.intellij.diff.DiffManager;
import com.intellij.diff.actions.impl.MutableDiffRequestChain;
import com.intellij.diff.contents.DocumentContent;
import com.intellij.diff.tools.simple.SimpleDiffTool;
import com.intellij.diff.util.DiffUserDataKeysEx;
import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeRegistry;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.search.PsiShortNamesCache;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.ArrayList;

import static com.dongbao.common.MessageConstant.CORE_CLASS_AUDIT_NOT_PASS_MESSAGE;
import static com.dongbao.common.MessageConstant.CORE_CLASS_AUDIT_PASS_MESSAGE;

public class CoreCodeAuditDialog extends JDialog {
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;

    private Project project;

    private MqMessage mqMessage;

    private JPanel javaEditorPanel;
    private JButton noPass;
    private JPanel auditRemarkPlan;
    private JTextArea remarkText;
    private JButton curentCodeDiff;

    private AuditFileInfo auditFileInfo;

    public CoreCodeAuditDialog(Project project, MqMessage mqMessage) {

        this.project = project;
        this.mqMessage = mqMessage;

        this.auditFileInfo = JSON.parseObject(mqMessage.getData().toString(), AuditFileInfo.class);

        /* 审核通过 */
        buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                CoreCodeAuditDialog.this.onOK();
            }
        });

        /* 审核不通过 */
        noPass.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                CoreCodeAuditDialog.this.noPassSendMessage();
            }
        });

        /* 打开本地代码对比弹窗 */
        curentCodeDiff.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                PsiFile[] filesByName = PsiShortNamesCache.getInstance(project).getFilesByName(auditFileInfo.getFileName());
                String oldContent = "";
                if(filesByName.length>0){
                    oldContent = filesByName[0].getText();
                }
                DocumentContent content1 = createEditableContent(project, StringUtil.notNullize(oldContent));
                DocumentContent content2 = createEditableContent(project, auditFileInfo.getContent());

                MutableDiffRequestChain chain = new MutableDiffRequestChain(content1, content2);
                chain.putUserData(DiffUserDataKeysEx.FORCE_DIFF_TOOL, SimpleDiffTool.INSTANCE);

                chain.putUserData( Key.create("Diff.BlankWindow"), true);
                DiffManager.getInstance().showDiff(project, chain, DiffDialogHints.DEFAULT);
            }
        });

        buttonCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

        // call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        // call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

        setContentPane(contentPane);
        setModal(false);
        getRootPane().setDefaultButton(buttonOK);
    }

    private DocumentContent createEditableContent(Project project,String text){
        return DiffContentFactoryEx.getInstanceEx().documentContent(project, false).buildFromText(text, false);
    }

    /**
     * 审核不通过按钮事件
     * */
    private void noPassSendMessage(){
        /* 审核通过 发送消息给提交审核信息的客户端 */
        String ip = Datacenter.clientIp;

        MqMessage auditMessage = MqMessage.getInstance();
        StringBuffer sb=new StringBuffer();
        sb.append("您的代码审核不通过:");
        for(Object item:mqMessage.getRows()){
            sb.append("[");
            sb.append(item);
            sb.append("]");
        }
        sb.append("<br/>审核人:"+Datacenter.clientIp);
        sb.append("<br/>审批意见:"+this.remarkText.getText());
        auditMessage.setMessage(sb.toString());
        auditMessage.setCode(CORE_CLASS_AUDIT_NOT_PASS_MESSAGE);
        auditMessage.setRows(mqMessage.getRows());

        AuditInfo auditInfo=new AuditInfo();
        auditInfo.setAuditLeaderIp(Datacenter.clientIp);
        auditInfo.setFiles(mqMessage.getRows());
        auditInfo.setOpinion(this.remarkText.getText());
        auditMessage.setData(auditInfo);
        Datacenter.myMqttClient.publishMessage(MyMqttClient.TOPIC_PREFIX+mqMessage.getAutoIp(), JSON.toJSONString(auditMessage),1);
        dispose();
    }

    /**
     * 审核通过按钮事件
     * */
    private void onOK() {
        /* 审核通过 发送消息给提交审核信息的客户端 */
        String ip = Datacenter.clientIp;

        MqMessage auditMessage = MqMessage.getInstance();
        StringBuffer sb=new StringBuffer();
        sb.append("您的代码审核已通过,可以进行提交操作:");
        for(Object item:mqMessage.getRows()){
            sb.append("[");
            sb.append(item);
            sb.append("]");
        }
        auditMessage.setMessage(sb.toString());
        auditMessage.setCode(CORE_CLASS_AUDIT_PASS_MESSAGE);
        auditMessage.setRows(mqMessage.getRows());
        Datacenter.myMqttClient.publishMessage(MyMqttClient.TOPIC_PREFIX+mqMessage.getAutoIp(), JSON.toJSONString(auditMessage),1);
        dispose();
    }

    private void onCancel() {
        /* 直接关闭 啥都不干,默认为审核不通过 */
        dispose();
    }

    /**
     * 打开窗口
     */
    public void open() {
        pack();
        setTitle("提交代码审核["+mqMessage.getAutoIp()+"]");
        setMinimumSize(new Dimension(800, 600));
        //两个屏幕处理出现问题，跳到主屏幕去了
        setLocationRelativeTo(WindowManager.getInstance().getFrame(this.project));
        setVisible(true);
    }

    public static void main(String[] args) {
//        CoreCodeAuditDialog dialog = new CoreCodeAuditDialog();
//        dialog.pack();
//        dialog.setVisible(true);
//        System.exit(0);
    }

    private void createUIComponents() {
        ArrayList<EditorHighlighterEx> highlighter=new ArrayList<>();
        EditorHighlighterEx highlighterEx=new EditorHighlighterEx();
        highlighterEx.setStartOffset(120);
        highlighterEx.setEndOffset(150);
        highlighter.add(highlighterEx);
        /* 创建代码编辑框组件 */
        javaEditorPanel = new MyLanguageTextField(project,  JavaLanguage.INSTANCE, JavaFileType.INSTANCE,highlighter);
        //设置高度固定搜索框
        javaEditorPanel.setMinimumSize(new Dimension(-1, 120));
        javaEditorPanel.setPreferredSize(new Dimension(-1, 120));
        javaEditorPanel.setMaximumSize(new Dimension(-1, 1000));

        if(this.auditFileInfo == null){
            this.auditFileInfo = JSON.parseObject(mqMessage.getData().toString(), AuditFileInfo.class);
        }

        ((MyLanguageTextField) javaEditorPanel).setText(auditFileInfo.getContent());
    }
}
